package com.ref;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class TestRef2 {


    @Test
    public void run() throws Exception {
        Class<Dog> dogClass = Dog.class;
        //获取该类是否存在注解
        MyComponent annotation = dogClass.getAnnotation(MyComponent.class);
        if (null != annotation) {

            Constructor<Dog> constructor = dogClass.getConstructor(null);
            Dog dog = constructor.newInstance(null);
            //开始赋值
            Field[] declaredFields = dogClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                MyValue myValue = declaredField.getAnnotation(MyValue.class);
                if (myValue!=null){
//                    System.out.println("添加了MyValue注解");
                    String value = myValue.value();
                    System.out.println(declaredField + "注解的值是" + value);
                    declaredField.setAccessible(true);
                    //判断属性类型
                    String name = declaredField.getType().getName();
                    System.out.println(name);
                    if (name.equals("java.lang.Integer")){
                        Integer val = Integer.parseInt(value);
                        declaredField.set(dog,val);
                    }else {
                        declaredField.set(dog,value);
                    }
                }
            }
            System.out.println(dog);
        } else {
            System.out.println("无法创建对象");
        }
    }
}
